# 用户路由
from flask import jsonify, request
from services.user_service import get_all_users, get_user_by_id, create_user, update_user, delete_user


def register_user_routes(app):
    """注册用户相关路由
    
    Args:
        app: Flask应用实例
    """
    @app.route('/users', methods=['GET'])
    def get_users():
        users = get_all_users()
        return jsonify([{
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'created_at': user.created_at.isoformat()
        } for user in users])
        
    @app.route('/users/<int:user_id>', methods=['GET'])
    def get_user(user_id):
        user = get_user_by_id(user_id)
        if not user:
            return jsonify({'error': 'User not found'}), 404
        return jsonify({
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'created_at': user.created_at.isoformat()
        })
        
    @app.route('/users', methods=['POST'])
    def add_user():
        data = request.get_json()
        if not data or 'username' not in data or 'email' not in data:
            return jsonify({'error': 'Username and email are required'}), 400
        
        try:
            new_user = create_user(data['username'], data['email'])
            return jsonify({
                'id': new_user.id,
                'username': new_user.username,
                'email': new_user.email,
                'created_at': new_user.created_at.isoformat()
            }), 201
        except Exception as e:
            return jsonify({'error': str(e)}), 400
            
    @app.route('/users/<int:user_id>', methods=['PUT'])
    def update_user_route(user_id):
        data = request.get_json()
        if not data:
            return jsonify({'error': 'No data provided'}), 400
            
        updated_user = update_user(user_id, data.get('username'), data.get('email'))
        if not updated_user:
            return jsonify({'error': 'User not found'}), 404
            
        return jsonify({
            'id': updated_user.id,
            'username': updated_user.username,
            'email': updated_user.email,
            'created_at': updated_user.created_at.isoformat()
        })
        
    @app.route('/users/<int:user_id>', methods=['DELETE'])
    def delete_user_route(user_id):
        success = delete_user(user_id)
        if not success:
            return jsonify({'error': 'User not found'}), 404
        return jsonify({'message': 'User deleted successfully'}), 200